import numpy as np

def hilbert_matrix(n):
    """
    生成n阶Hilbert矩阵
    
    参数:
    n (int): Hilbert矩阵的阶数
    
    返回:
    np.ndarray: 生成的n阶Hilbert矩阵
    """
    # 创建一个空的n x n矩阵
    H = np.zeros((n, n))
    # 填充矩阵元素
    for i in range(n):
        for j in range(n):
            H[i, j] = 1 / (i + j + 1)
    return H

def condition_number(H):
    """计算矩阵的条件数"""
    return np.linalg.cond(H, 2)  # 2表示无穷范数

# 对n = 2, 4, 6, 8, 10计算条件数
n_values = [2, 4, 6, 8, 10]
for n in n_values:
    H = hilbert_matrix(n)
    cond_H = condition_number(H)
    print(f"条件数cond(H_{n})∞: {cond_H}")


#求解线性方程组并分析数位变化
def compute_b(H):
    """计算b = Hx，其中x是全1向量"""
    x = np.ones(H.shape[0])
    b = np.dot(H, x)
    return b

def solve_linear_system(H, b):
    """求解线性方程组Hx = b"""
    return np.linalg.solve(H, b)

# 求解线性方程组并分析有效数字位数
for n in range(9, 21):
    H = hilbert_matrix(n)
    b = compute_b(H)
    x = solve_linear_system(H, b)
    print(f"n = {n}时，解向量x: {x}")
